package com.faithnmn.learnenglishbc.service;

import java.io.IOException;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.faithnmn.learnenglishbc.MainActivity;
import com.faithnmn.learnenglishbc.R;
import com.faithnmn.learnenglishbc.network.Downloader;
import com.faithnmn.learnenglishbc.util.Constants;
import com.faithnmn.learnenglishbc.util.LoadNextLessonUtil;
import com.faithnmn.learnenglishbc.util.StorageUtil;

public class LessionsPlayer extends Service {
	
	private static RemoteViews contentRemoteViews;
	private NotificationManager notiManager;
	private static Notification notification;
	private static MediaPlayer mediaPlayer;
	private static SharedPreferences sharedPreferences;
	public static int currentSeriIndex,currentLessionIndex;
	private static LessionsPlayer instance;
	private ServiceReceiver serviceReceiver = new ServiceReceiver();
	private static final int NOTIFICATION_ID = 233223;
	
	@Override
	public void onCreate() {
		super.onCreate();
		sharedPreferences = getSharedPreferences("LEBCBC", MODE_PRIVATE);
		instance = this;
		IntentFilter serviceReceiverFilters = new IntentFilter();
		serviceReceiverFilters.addAction(Constants.PLAYER_PLAY_PAUSE_ACTION);
		serviceReceiverFilters.addAction(Constants.PLAYER_CLOSE_ACTION);
		serviceReceiverFilters.addAction(Constants.NOTIFY_NEW_DATA_LESSION);
		serviceReceiverFilters.addAction(Constants.NOTIFY_AUDIO_READY_ACTION);
		registerReceiver(serviceReceiver, serviceReceiverFilters);
		
		
		notification = new Notification();
		notification.icon = R.drawable.ic_launcher;
		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		
		Intent notifyIntent = null;
		if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
			notifyIntent = new Intent();
		}else{
			notifyIntent = new Intent("notification");
		}
		notifyIntent.setClass(this, MainActivity.class);
	    PendingIntent pending = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		contentRemoteViews = new RemoteViews(getPackageName(), R.layout.player_noti_layout);
		Intent playPauseIntent=new Intent(Constants.PLAYER_PLAY_PAUSE_ACTION);
		PendingIntent playPauseNotiIntent=PendingIntent.getBroadcast(this, 0, playPauseIntent, 0);
		Intent closeIntent=new Intent(Constants.PLAYER_CLOSE_ACTION);
		PendingIntent closeNotiIntent=PendingIntent.getBroadcast(this, 0, closeIntent, 0);
		notification.contentIntent = pending;
		contentRemoteViews.setOnClickPendingIntent(R.id.playPause, playPauseNotiIntent);
		contentRemoteViews.setOnClickPendingIntent(R.id.close, closeNotiIntent);
		notification.contentView = contentRemoteViews;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if(intent != null && intent.getAction()!= null && intent.getAction().equals(Constants.PLAY_LESSION_ACTION)){
			String audioName = intent.getStringExtra("audioName");
			String title = intent.getStringExtra("title");
			int currentSeriIndex = intent.getIntExtra("currentSeriIndex", 0);
			int currentLessionIndex = intent.getIntExtra("currentLessionIndex", 0);
			prepareLoadAudio(audioName, title, currentSeriIndex, currentLessionIndex);
		}else if(intent != null && intent.getAction() != null && intent.getAction().equals(Constants.PLAYER_PLAY_PAUSE_ACTION)){
			playPausePlayer();
		}else if(intent != null && intent.getAction() != null && intent.getAction().equals(Constants.PLAYER_CLOSE_ACTION)){
			stopPlayer();
		}
		return START_STICKY;
	}

	private void playPausePlayer() {
		if(mediaPlayer != null){
			if(mediaPlayer.isPlaying()){
				mediaPlayer.pause();
				contentRemoteViews.setTextViewText(R.id.playPause, "Play");
			}else{
				contentRemoteViews.setTextViewText(R.id.playPause, "Pause");
				mediaPlayer.start();
			}
			startForeground(NOTIFICATION_ID, notification);
		}
	}

	private void stopPlayer() {
		if(mediaPlayer != null){
			mediaPlayer.release();
			mediaPlayer = null;
			notiManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
			notiManager.cancelAll();
			stopSelf();
		}
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public static MediaPlayer getMediaplayer(){
		return mediaPlayer;
	}
	
	private static void initMediaplayer(String path,int currentSeriIndex,int currentLessionIndex){
		Log.e("initMedia", "initMedia:"+path);
		if(mediaPlayer != null){
			try {
				if(mediaPlayer != null && mediaPlayer.isPlaying()){
					LessionsPlayer.mediaPlayer.stop();
					LessionsPlayer.mediaPlayer.release();
				}
			} catch (IllegalStateException e) {
				if(LessionsPlayer.mediaPlayer != null){
					LessionsPlayer.mediaPlayer.release();
				}
			}
		}
		mediaPlayer = new MediaPlayer();
		try {
			mediaPlayer.setDataSource(getContext(), Uri.parse(path));
			LessionsPlayer.mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			LessionsPlayer.mediaPlayer.setWakeMode(getContext(), PowerManager.PARTIAL_WAKE_LOCK);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		LessionsPlayer.currentSeriIndex = currentSeriIndex;
		LessionsPlayer.currentLessionIndex = currentLessionIndex;
		LessionsPlayer.mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				if(getPlaymodeAll()){
					doPlayNextLession();
					Toast.makeText(getContext(), "\u0110ang m\u1EDF b\u00E0i ti\u1EBFp theo!", Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	
	public static boolean isPlayingMe(int currentSeriIndex, int currentLessionIndex){
		if(LessionsPlayer.currentLessionIndex == currentLessionIndex && currentSeriIndex == LessionsPlayer.currentSeriIndex){
			return true;
		}else return false;
	}
	
	public static void savePlaymode(boolean all){
		sharedPreferences.edit().putBoolean("play_all", all).commit();
	}
	
	public static boolean getPlaymodeAll(){
		return sharedPreferences.getBoolean("play_all", false);
	}
	
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	private void prepareLoadAudio(String audioName,final String title,int currentSeriIndex,int currentLessionIndex) {
		LessionsPlayer.currentSeriIndex = currentSeriIndex;
		LessionsPlayer.currentLessionIndex = currentLessionIndex;
		
		if(!StorageUtil.checkAudioAvailable(audioName)){
			Downloader downloader = new Downloader(this);
			downloader.execute(com.faithnmn.learnenglishbc.util.Constants.URL+audioName+".mp3",title,audioName);
		}else{
			try {
				LessionsPlayer.initMediaplayer(StorageUtil.AUDIO_FOLDER+"/"+audioName+".mp3",currentSeriIndex,currentLessionIndex);
				LessionsPlayer.getMediaplayer().setOnPreparedListener(new OnPreparedListener() { 
			        @Override
			        public void onPrepared(MediaPlayer mp) {
			            mp.start();
			            Intent mediaPlaying = new Intent(Constants.NOTIFY_AUDIO_READY_ACTION);
			            mediaPlaying.putExtra("done", true);
			            mediaPlaying.putExtra("immediate", true);
			            sendBroadcast(mediaPlaying);
			            contentRemoteViews.setTextViewText(R.id.title, title);
			            contentRemoteViews.setTextViewText(R.id.playPause, "Pause");
			            notification.when = System.currentTimeMillis();
			            if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN){
			            	notification.priority = Notification.PRIORITY_MAX;
			            }
						startForeground(NOTIFICATION_ID, notification);
			        }
			    });
				LessionsPlayer.getMediaplayer().prepareAsync();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void onDestroy() {
		Log.e("onDestroy", "onDestroy:LessionsPlayer");
		unregisterReceiver(serviceReceiver);
		super.onDestroy();
	}
	
	@SuppressLint("NewApi")
	public static void doPlayNextLession(){
		if(currentLessionIndex < 11){
			currentLessionIndex +=1;
		}else{
			currentLessionIndex = 0;
			currentSeriIndex +=1;
		}
		if(currentSeriIndex == 4){
			currentSeriIndex = 0;
			Toast.makeText(getContext(), "\u0110\u00E3 nghe h\u1EBFt to\u00E0n b\u1ED9!", Toast.LENGTH_LONG).show();
			return;
		}
		ArrayList<String> lessonInfo = LoadNextLessonUtil.loadNextLessionAudioInfo(currentSeriIndex, currentLessionIndex);
		Intent lessionData = new Intent(Constants.NOTIFY_NEW_DATA_LESSION);
		if(!StorageUtil.checkAudioAvailable(lessonInfo.get(0))){
			//download audio
			Downloader downloader = new Downloader(getContext());
			downloader.execute(com.faithnmn.learnenglishbc.util.Constants.URL+lessonInfo.get(0)+".mp3",lessonInfo.get(1),lessonInfo.get(0));
			lessionData.putExtra("ready", false);
		}else{
			//notify Lesson Fragment to load new data
			lessionData.putExtra("ready", true);
			initMediaplayer(StorageUtil.AUDIO_FOLDER+"/"+lessonInfo.get(0)+".mp3",currentSeriIndex,currentLessionIndex);
			LessionsPlayer.getMediaplayer().setOnPreparedListener(new OnPreparedListener() { 
		        @Override
		        public void onPrepared(MediaPlayer mp) {
		            mp.start();
		        }
		    });
			LessionsPlayer.getMediaplayer().prepareAsync();
			lessionData.putExtra("audioName", lessonInfo.get(0));
			lessionData.putExtra("lessionTitle", lessonInfo.get(1));
			lessionData.putExtra("currentSeriIndex", currentSeriIndex);
			lessionData.putExtra("currentLessionIndex", currentLessionIndex);
			lessionData.putExtra("data",lessonInfo.get(2));
			contentRemoteViews.setTextViewText(R.id.title, lessonInfo.get(1));
			notification.when = System.currentTimeMillis();
            if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN){
            	notification.priority = Notification.PRIORITY_MAX;
            }
			instance.startForeground(NOTIFICATION_ID, notification);
			LocalBroadcastManager.getInstance(getContext()).sendBroadcast(lessionData);
		}
		
	}
	
	public static Context getContext(){
		return instance;
	}
	
	private class ServiceReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent != null && intent.getAction()!= null && intent.getAction().equals(Constants.NOTIFY_NEW_DATA_LESSION)){
				String audioReadyName = intent.getStringExtra("audioName");
				String lessionTitle = intent.getStringExtra("lessionTitle");
				int currentSeri = intent.getIntExtra("currentSeriIndex", 0);
				int currentLession = intent.getIntExtra("currentLessionIndex", 0);
				boolean ready = intent.getBooleanExtra("ready", false);
				if(ready){
					if(TextUtils.isEmpty(audioReadyName) || audioReadyName.equalsIgnoreCase("null")){
						
					}else{
						prepareLoadAudio(audioReadyName,lessionTitle,currentSeri,currentLession);
					}
					
				}else{
					Toast.makeText(context, "T\u1EA3i \u00E2m thanh th\u1EA5t b\u1EA1i, th\u1EED l\u1EA1i sau", Toast.LENGTH_LONG).show();
				}
			}else if(intent != null && intent.getAction()!= null && intent.getAction().equals(Constants.PLAYER_CLOSE_ACTION)){
				stopPlayer();
			}else if(intent != null && intent.getAction()!= null && intent.getAction().equals(Constants.PLAYER_PLAY_PAUSE_ACTION)){
				playPausePlayer();
			}
			else if(intent != null && intent.getAction()!= null && intent.getAction().equals(Constants.NOTIFY_AUDIO_READY_ACTION)){
				String title = intent.getStringExtra("lessionTitle");
				String audioName= intent.getStringExtra("audioName");
				if(TextUtils.isEmpty(audioName) || audioName.equalsIgnoreCase("null")){
					
				}else{
					prepareLoadAudio(audioName, title, currentSeriIndex, currentLessionIndex);
				}
				
			}
		}
		
	}
}
